package com.android.vestel.photoroid;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.HashMap;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

import android.util.Log;

class PicasaClient extends WebPhotos {

	private String username;
	private String password;
	private String auth;
	private String userID;
	private ArrayList<String> imagePaths = new ArrayList<String>();
	private ArrayList<String> albumIDs = new ArrayList<String>();
	private ArrayList<String> imageIDs = new ArrayList<String>();
	private ArrayList<String> albumNames = new ArrayList<String>();
	private HashMap<String, String> images = new HashMap<String, String>();

	public PicasaClient() {
		this.username = null;
		this.password = null;
		this.auth = null;
	}

	public PicasaClient(String username, String password) {
		this.username = username;
		this.password = password;
	}

	public String getUsername() {
		return username;
	}

	public String getPassword() {
		return password;
	}

	public String getAuth() {
		return auth;
	}

	public ArrayList<String> getImagePaths() {
		return imagePaths;
	}

	public ArrayList<String> getImageIDs() {
		return imageIDs;
	}

	public ArrayList<String> getAlbumIDs() {
		return albumIDs;
	}

	public ArrayList<String> getAlbumNames() {
		return albumNames;
	}

	public String getUserID() {
		return userID;
	}

	public HashMap<String, String> getImages() {
		return images;
	}

	public boolean OpenAuthentication() {
		try {
			if (username.trim().length() == 0 || password.trim().length() == 0) {
				return false;
			}
			String authUrl = "https://www.google.com/accounts/ClientLogin?accountType=GOOGLE&Email="
					+ username
					+ "&Passwd="
					+ password
					+ "&service=lh2&source=PicasaUploader";
			SSLContext sc = SSLContext.getInstance("TLS");

			sc.init(null, new TrustManager[] { new MyTrustManager() },
					new SecureRandom());

			HttpsURLConnection
					.setDefaultSSLSocketFactory(sc.getSocketFactory());
			HttpsURLConnection
					.setDefaultHostnameVerifier(new MyHostnameVerifier());
			HttpsURLConnection con = (HttpsURLConnection) new URL(authUrl)
					.openConnection();

			con.setReadTimeout(30000);
			con.setDoOutput(true);
			con.connect();

			BufferedReader br = new BufferedReader(new InputStreamReader(
					con.getInputStream()));
			StringBuffer sb = new StringBuffer();
			String line;

			while ((line = br.readLine()) != null) {
				sb.append(line);
			}

			String body = sb.toString();
			Integer index = body.indexOf("Auth=");

			if (index != -1) {
				auth = body.substring(index + 5);
				parseAlbumIDs();
				return true;
			}
		} catch (Exception e) {
			Log.e("Open Authentication Exception", e.toString());
			return false;
		}
		return false;
	}

	private String fetchUrl(String Url) {
		try {

			HttpURLConnection con = (HttpURLConnection) new URL(Url)
					.openConnection();

			con.setRequestMethod("GET");
			con.setReadTimeout(30000);
			con.setRequestProperty("Authorization", "GoogleLogin auth=" + auth);
			con.setRequestProperty("GData-Version", "2");

			con.setReadTimeout(30000);
			con.setDoOutput(true);
			con.connect();

			BufferedReader reader = new BufferedReader(new InputStreamReader(
					con.getInputStream()));
			StringBuilder builder = new StringBuilder();
			String line;

			while ((line = reader.readLine()) != null) {
				builder.append(line + "\n");
			}
			return builder.toString();
		} catch (Exception e) {
			Log.e("Fetch URL Error ", e.toString());
			e.printStackTrace();
			return null;
		}
	}

	public void parseAlbumIDs() {
		try {
			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
			DocumentBuilder db = dbf.newDocumentBuilder();
			InputSource is = new InputSource();

			String xml = fetchUrl("http://picasaweb.google.com/data/feed/api/user/"
					+ username);

			is.setCharacterStream(new StringReader(xml));
			Document doc = db.parse(is);
			NodeList entries = doc.getElementsByTagName("entry");

			for (int i = 0; i < entries.getLength(); i++) {
				Element elem = (Element) entries.item(i);
				Element id = (Element) elem.getElementsByTagName("id").item(0);
				albumNames.add(elem.getElementsByTagName("title").item(0)
						.getTextContent());
				albumIDs.add(id.getTextContent().substring(
						id.getTextContent().lastIndexOf("/") + 1));
			}
			/* Setting userID according to the fetched url */
			Element elem = (Element) entries.item(0);
			Element id = (Element) elem.getElementsByTagName("id").item(0);

			String part = id.getTextContent().substring(
					id.getTextContent().indexOf("user/") + 5);
			String[] s = part.toString().split("/");
			this.userID = s[0];

		} catch (Exception e) {
			Log.e("Album Parsing Error", e.toString());
			e.printStackTrace();
			return;
		}
	}

	public void parsePhotos(String albumID) {
		try {
			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
			DocumentBuilder db = dbf.newDocumentBuilder();
			InputSource is = new InputSource();
			String tempImageID = null;
			String tempImagePath = null;

			String xml = fetchUrl("http://picasaweb.google.com/data/feed/api/user/"
					+ this.userID + "/albumid/" + albumID);
			if(xml == null){
				Log.e("PicasaClient","xml is null");
			}
			is.setCharacterStream(new StringReader(xml));
			Document doc = db.parse(is);
			NodeList entries = doc.getElementsByTagName("entry");
			for (int l = 0; l < entries.getLength(); l++) {
				Element elem = (Element) entries.item(l);

				tempImageID = elem.getElementsByTagName("gphoto:id").item(0)
						.getTextContent();
				imageIDs.add(tempImageID);

				for (int k = 0; k < elem.getElementsByTagName("media:group")
						.getLength(); k++) {
					NodeList mediagroup = elem
							.getElementsByTagName("media:group").item(k)
							.getChildNodes();

					for (int j = 0; j < mediagroup.getLength(); j++) {
						Element element = (Element) mediagroup.item(j);
						if (element.getTagName().equals("media:content")) {
							tempImagePath = element.getAttribute("url");
							imagePaths.add(tempImagePath);
						}
					}
				}
				if(tempImageID != null && tempImagePath != null ){
					images.put(tempImageID, tempImagePath);
				}
			}

		} catch (Exception e) {
			Log.e("Parsing Paths of the Photos Error ", e.toString());
			e.printStackTrace();
		}
	}

	private class MyHostnameVerifier implements HostnameVerifier {
		@Override
		public boolean verify(String hostname, SSLSession session) {
			return true;
		}
	}

	private class MyTrustManager implements X509TrustManager {
		@Override
		public void checkClientTrusted(X509Certificate[] chain, String authType) {
		}

		@Override
		public void checkServerTrusted(X509Certificate[] chain, String authType) {
		}

		@Override
		public X509Certificate[] getAcceptedIssuers() {
			return null;
		}
	}
}